#!/bin/sh
#
# Start/stop/restart the FreeSWITCH daemon
# Written by Mario Preksavec <mario@slackware.hr>

USER=freeswitch
GROUP=freeswitch
BIN_FILE=/opt/freeswitch/bin/freeswitch
PID_FILE=/var/run/freeswitch/freeswitch.pid
RUN_ARGS="-nc -rp -nonat"

set_limits() {
  ulimit -c unlimited
  ulimit -d unlimited
  ulimit -f unlimited
  ulimit -i unlimited
  ulimit -n 999999
  ulimit -q unlimited
  ulimit -u unlimited
  ulimit -v unlimited
  ulimit -x unlimited
  ulimit -s 240
  ulimit -l unlimited
}

start() {
  echo -n "Starting FreeSWITCH: "
  if [ -e $PID_FILE ] && [ -e /proc/$(cat $PID_FILE) ]; then
    echo "Already running."
  else
    set_limits
    $BIN_FILE $RUN_ARGS -u $USER -g $GROUP >/dev/null 2>&1
    if [ $? -eq 0 ]; then
      echo "Started."
    else
      echo "Failed starting."
    fi
  fi
}

stop() {
  echo -n "Stopping FreeSWITCH: "
  if [ -e $PID_FILE ] && [ -e /proc/$(cat $PID_FILE) ]; then
    $BIN_FILE -stop >/dev/null 2>&1
    if [ $? -eq 0 ]; then
      echo "Stopped."
    else
      echo "Failed stopping."
    fi
  else
    echo "Not running."
  fi
}

case "$1" in
  start)
    start
  ;;
  stop)
    stop
  ;;
  restart)
    stop
    sleep 5
    start
  ;;
  *)
    echo "USAGE: $0 {start|stop|restart}"
  ;;
esac
